package handlers

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"qimo_work/models"
	"qimo_work/repositories"
)

// GetAllUsersHandler 获取所有用户（支持分页）
func GetAllUsersHandler(c *gin.Context) {
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil || page < 1 {
		page = 1
	}

	pageSize, err := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	if err != nil || pageSize < 1 {
		pageSize = 10
	}

	users, total, err := repositories.GetAllUsers(page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户列表失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"data":     users,
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
	})
}

// GetUserHandler 根据用户ID获取用户信息
func GetUserHandler(c *gin.Context) {
	// 获取用户ID
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户 ID"})
		return
	}

	// 从数据库获取用户信息
	user, err := repositories.GetUserByID(uint(id))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户失败", "details": err.Error()})
		return
	}

	// 返回用户数据
	c.JSON(http.StatusOK, gin.H{
		"data": user,
	})
}

// DeleteUserHandler 删除用户
func DeleteUserHandler(c *gin.Context) {
	// 获取用户 ID
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户 ID"})
		return
	}

	// 删除用户
	if err := repositories.DeleteUser(uint(id)); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除用户失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "用户已删除"})
}

// UpdateUserHandler 更新用户
func UpdateUserHandler(c *gin.Context) {
	// 获取用户 ID
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户 ID"})
		return
	}

	var user models.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": err.Error()})
		return
	}

	user.ID = uint(id)

	// 更新用户
	if err := repositories.UpdateUser(user); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新用户失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "用户更新成功", "data": user})
}
